<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="3">
        <el-select
          v-model="search.filter_project_id"
          filterable
          clearable
          placeholder="请选择项目"
          @change="fetchProjectData"
        >
          <el-option
            v-for="item in search.project_options"
            :key="item.id"
            :label="item.project_name"
            :value="item.id"
          />
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-input
          v-model="search.name"
          placeholder="请输入认证名称"
          prefix-icon="el-icon-search"
          @keyup.enter.native="SearchAuth()"
        />
      </el-col>
      <el-col :span="3">
        <el-button type="primary" icon="el-icon-search" round @click="SearchAuth()">搜索</el-button>
      </el-col>
    </el-row>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="ID" min-width="6%">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="认证名称" min-width="15%" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link
            style="color:#298abd"
            @click="edit(scope.row.id)"
          >{{ scope.row.name == '' ? '-' : scope.row.name }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="认证方式" min-width="12%">
        <template slot-scope="scope">
          {{ scope.row.auth_type }}
        </template>
      </el-table-column>
      <el-table-column label="认证用户" min-width="8%" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.user_name == null ? '-' : scope.row.user_name }}
        </template>
      </el-table-column>
      <el-table-column label="所属项目" min-width="10%" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.belong_project_name }}
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        min-width="15%"
        align="center"
        prop="更新时间"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ $common.formatDateTime(scope.row.update_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编写人员" min-width="10%" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.author }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="16%" align="center">
        <template slot-scope="scope">
          <el-button-group>
            <el-tooltip content="测试" placement="bottom" effect="light">
              <el-button
                size="mini"
                type="success"
                icon="el-icon-position"
                @click="run(scope.row.id)"
              />
            </el-tooltip>
            <el-tooltip content="编辑" placement="bottom" effect="light">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="edit(scope.row.id)"
              />
            </el-tooltip>
            <el-tooltip content="复制" placement="bottom" effect="light">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-copy-document"
                @click="copy(scope.row.id)"
              />
            </el-tooltip>
            <el-tooltip content="删除" placement="bottom" effect="light">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="del(scope.row.id)"
              />
            </el-tooltip>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="pagination.page_num"
      :page-sizes="[10, 20]"
      :page-size="pagination.page_size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      title="获取token为"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span>{{ token_map.token_key }} : {{ token_map.token_value }}
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="运行认证接口" :visible.sync="run_dialog.dialogFormVisible" width="30%">
      <el-form
        :model="run_dialog"
      >
        <el-form-item label="配置信息" label-width="120px" required>
          <el-select
            v-model="run_dialog.config_id"
            style="width:60%"
            filterable
            clearable
            placeholder="请选择运行配置"
          >
            <el-option
              v-for="item in run_dialog.config_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="run_dialog.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="run_test()">运 行</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAuthList, deleteAuth, testAuth } from '@/api/test_auth/table'
import { getProjectSumList } from '@/api/project/table'
import { getConfigSumList } from '@/api/config/table'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },

  data() {
    return {
      search: {
        project_options: [],
        filter_project_id: null,
        name: ''
      },
      pagination: {
        total: 0,
        page_current: 1,
        page_num: 1,
        page_size: 10
      },
      token_map: {
        token_key: '',
        token_value: ''
      },
      list: null,
      listLoading: true,
      ispagination: false,
      dialogVisible: false,
      run_dialog: {
        dialogFormVisible: false,
        auth_type: '',
        auth_id: '',
        url: null,
        config_id: '',
        config_list: []
      }
    }
  },

  created() {
    this.fetchAuthData()
    this.fetchProjectData()
  },

  methods: {
    fetchProjectData() {
      getProjectSumList().then(response => {
        this.search.project_options = response.results
      })
    },

    fetchAuthData() {
      var params = {}

      params['ordering'] = '-update_time'
      this.listLoading = true
      getAuthList(params).then(response => {
        this.list = response.results
        this.listLoading = false
        this.pagination.total = response.count
      })
    },

    SearchAuth() {
      var params = {}
      if (this.search.filter_project_id) {
        for (var i = 0; i < this.search.project_options.length; i++) {
          if (this.search.filter_project_id === this.search.project_options[i].id) {
            params['belong_project'] = this.search.project_options[i].id
          }
        }
      }
      if (this.search.name) {
        params['search'] = this.search.name
      }

      if (this.ispagination) {
        params['page_num'] = this.pagination.page_num
        params['page_size'] = this.pagination.page_size
      } else {
        params['page_num'] = 1
        params['page_size'] = this.pagination.page_size
      }
      params['ordering'] = '-update_time'

      this.listLoading = true
      getAuthList(params).then(response => {
        this.list = response.results
        this.listLoading = false
        this.pagination.total = response.count
      })
      if (this.ispagination === false) {
        this.pagination.page_num = 1
      }
      this.ispagination = false
    },

    fetchConfigSumList: function(val) {
      var params = {}
      params['belong_project'] = val

      getConfigSumList(params).then(response => {
        this.run_dialog.config_list = response.results
      })
    },

    run_test: function() {
      if (this.run_dialog.config_id === '') {
        this.run_dialog.dialogFormVisible = true
        this.$message({
          type: 'error',
          message: '请选择配置'
        })
      } else {
        var data = {}

        data['id'] = this.run_dialog.auth_id
        data['cfg_id'] = this.run_dialog.config_id

        testAuth(data).then(response => {
          this.token_map = response.data
          this.dialogVisible = true
        })
        this.run_dialog.dialogFormVisible = false
      }
    },

    run(id) {
      this.run_dialog.auth_id = Number(id)
      for (var i = 0; i < this.list.length; i++) {
        if (this.list[i].id === this.run_dialog.auth_id) {
          if (this.list[i].auth_type === 'Custom Authentication') {
            this.run_dialog.url = this.list[i].auth_url
          }
          this.fetchConfigSumList(this.list[i].belong_project)
          this.run_dialog.auth_type = this.list[i].auth_type
        }
      }

      var data = {}
      data['id'] = id
      data['cfg_id'] = null
      if (this.run_dialog.auth_type === 'Basic Authentication') {
        testAuth(data).then(response => {
          this.token_map = response.data
          this.dialogVisible = true
        })
      } else {
        console.log(this.run_dialog.url)
        if (this.run_dialog.url === '' || (this.run_dialog.url.startsWith('@@@') && this.run_dialog.url.endsWith('@@@'))) {
          this.run_dialog.dialogFormVisible = true
        } else {
          testAuth(data).then(response => {
            this.token_map = response.data
            this.dialogVisible = true
          })
        }
      }
    },

    edit(arg) {
      this.$router.push({
        path: '/test_auth/update_auth',
        query: {
          id: arg,
          operation_type: 1
        }
      })
    },

    copy(arg) {
      this.$router.push({
        path: '/test_auth/create_auth',
        query: {
          id: arg,
          operation_type: 2
        }
      })
    },

    del(arg) {
      this.$confirm('此操作将删除该认证信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = {}
        params['id'] = arg
        deleteAuth(params).then(response => {
          if (response.success === 'true') return
          this.SearchAuth()
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    handleSizeChange: function(val) {
      this.pagination.page_size = val
      this.SearchAuth()
    },

    handleCurrentChange: function(val) {
      this.ispagination = true
      this.pagination.page_num = val
      this.SearchAuth()
    }
  }
}
</script>
